<?php
App::uses('AppController', 'Controller');
/**
 * Logins Controller
 *
 * @property Login $Login
 */
class LoginController extends AppController {

/**
 * index method
 *
 * @return void
 */
	public function index() {
		if(!$this->Auth->loggedIn()){
			$this->set('login_page','1');
			if ($this->request->is('post')) {
				$this->request->data['Usuario']['email'] = $this->request->data['Login']['login'];
				$this->Login->Usuario->set($this->request->data);
				if (!$this->Login->Usuario->validates(array('fieldList' => array('email')))){
					$usuario = $this->Login->Usuario->findByEmail($this->request->data['Login']['login']);
					if($usuario)
						$this->request->data['Login']['login'] = $usuario['Login']['login'];
				}
				if ($this->Auth->login()) {
					$usuario = $this->Auth->user();
					if($usuario['ativado']){
						if($usuario['tipo'] == ADMIN || $usuario['tipo'] == ADMIN_LOCAL)
							return $this->redirect('/pages/blank');
						elseif($usuario['tipo'] == RECEPCIONISTA) return $this->redirect('/usuarios/recepcionista');
						return $this->redirect('/usuarios/view');
					}
					else{
						$this->Session->setFlash(__('Sua conta ainda não foi ativada!'), 'flash/bootstrap', array('class'=>'alert alert-block'));
						$this->logoutNaoAtivado();
					}
				} else {
					$this->Session->setFlash(__('Usuário ou senha incorretos'), 'flash/bootstrap', array('class'=>'alert alert-error'), 'auth');
					unset($this->request->data['Login']['senha']);
				}
			}
		}
		else 
			$this->redirect('/');
	}
	
	public function logout(){
		$this->Auth->logout();
		$this->Session->destroy();
		$this->redirect(array('action' => 'index'));
	}
	
	public function logoutNaoAtivado(){
		$this->Auth->logout();
		$this->redirect(array('action' => 'index'));
	}
	
	public function alterar_senha(){
		if($this->Auth->loggedIn()){
			if ($this->request->is('post') || $this->request->is('put')) {
				$options = array('conditions' => array('Login.' . $this->Login->primaryKey => $this->Auth->user('id')), 'recursive' => -1);
				$data = $this->Login->find('first', $options);
				if($this->Login->chkPasswd($this->request->data['Login']['senha_atual'])){
					$data['Login']['senha'] = $this->request->data['Login']['senha'];
					$data['Login']['confirmacao_senha'] = $this->request->data['Login']['confirmacao_senha'];
					if ($this->Login->save($data)) {
						$this->Session->setFlash(__('A senha foi alterada com sucesso'));
						$this->redirect('/pages/blank');
					} 
				}
				else {
					$this->Session->setFlash(__('Erro ao alterar a senha'));
					$this->request->data['Login']['senha_atual'] = '';
					$this->request->data['Login']['senha'] = '';
					$this->request->data['Login']['confirmacao_senha'] = '';
				}
			}
		}
		else
			$this->redirect('/');
	}

}
